package com.lsz.flight_system.controller;

import com.lsz.flight_system.entity.Admin;
import com.lsz.flight_system.entity.BuyTicketsMessage;
import com.lsz.flight_system.entity.PlaneMessage;
import com.lsz.flight_system.entity.UserMessage;
import com.lsz.flight_system.service.BuyTicketsMessageService;
import com.lsz.flight_system.service.PlaneMessageService;
import com.lsz.flight_system.service.UserMessageService;
import com.lsz.flight_system.utils.PhoneCheckUtils;
import com.lsz.flight_system.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/userMessage")
public class UserMessageController {

    @Autowired
    UserMessageService userMessageService;

    @Autowired
    BuyTicketsMessageService buyTicketsMessageService;

    @Autowired
    PlaneMessageService planeMessageService;

    private UserMessage message = new UserMessage();

    //用户修改自身信息
    @GetMapping("/userUpdateMessage")
    public Result userUpdateUserMessage(@RequestParam String username,
                                        @RequestParam String password,
                                        @RequestParam String phone,
                                        HttpSession session){
        UserMessage userMessage = (UserMessage) session.getAttribute("USER_MESSAGE");
        if (userMessage == null){
            return Result.fail("请登录后进行修改");
        }
        if (username.equals("")||password.equals("")||phone.equals("")){
            return Result.fail("有必填项未填写");
        }
        if (!PhoneCheckUtils.isChinaPhoneLegal(phone)){
            return Result.fail("手机号格式错误");
        }
        userMessage.setPassword(password);
        userMessage.setPhone(phone);
        if (userMessage.getUsername().equals(username)){
            if (userMessageService.saveUserMessage(userMessage)){
                return Result.ok();
            }
            return Result.fail("修改异常");
        }else {
//            userMessageService.delUserMessageByUsername(userMessage.getUsername());
            if (userMessageService.getUserMessageByUsername(username)!=null){
//                userMessageService.saveUserMessage(userMessage);
                return Result.fail("该用户名存在，修改失败");
            }
            userMessageService.delUserMessageByUsername(userMessage.getUsername());
            userMessage.setUsername(username);
            if (userMessageService.saveUserMessage(userMessage)){
                return Result.ok();
            }
            return Result.fail("修改异常");
        }
    }

    //用户余额充值
    @GetMapping("/userRecharge/{money}")
    public Result userRecharge(@PathVariable float money,HttpSession session){
        UserMessage userMessage = (UserMessage) session.getAttribute("USER_MESSAGE");
        try {
            if(userMessageService.userRecharge(userMessage.getUsername(),money))
                return Result.ok();
            return Result.fail("充值异常");
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("请登录后进行充值");
        }
    }

    //用户余额提现，仅支持全额提现
    @PostMapping("/userWithdraw")
    public Result userWithdraw(HttpSession session){
        UserMessage userMessage = (UserMessage) session.getAttribute("USER_MESSAGE");
        try {
            UserMessage message = userMessageService.getUserMessageByUsername(userMessage.getUsername());
            if (message.getBalance() == 0){
                return Result.fail("余额为0无法提现");
            }
            userMessageService.userWithdraw(message.getUsername());
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("请登录后进行提现");
        }
    }

    //用户信息页，根据登录的session查询并展示用户信息
    @PostMapping("/message")
    public Result userMessage(HttpSession session){
        UserMessage userMessage = (UserMessage) session.getAttribute("USER_MESSAGE");
//        System.out.println(userMessage);
        try {
            UserMessage message = userMessageService.getUserMessageByUsername(userMessage.getUsername());
            return Result.ok(message);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("请登录后查看");
        }
    }
    //用户退票接口
    @PostMapping("/backTicket/{id}")
    public Result userBackTicket(@PathVariable Long id){
        BuyTicketsMessage buyTicketsMessage = buyTicketsMessageService.findBuyTicketsMessageById(id);
        PlaneMessage planeMessage = planeMessageService.findByPlaneId(buyTicketsMessage.getPlaneId());
        LocalDateTime endTime = planeMessage.getStartTime();
        //当前时间增加一小时
        LocalDateTime backTime = LocalDateTime.now().plusHours(1);
        if (endTime.isBefore(backTime)){
            return Result.fail("飞机即将起飞，无法退票");
        }
        if(buyTicketsMessageService.userBackTickets(id)){
            return Result.ok();
        }
        return Result.fail("退票异常");
    }
    //保存用户所要换购的票的信息
    @PostMapping("/changeMessage/{id}")
    public Result userChangeTickets(@PathVariable Long id, HttpSession session){
        BuyTicketsMessage buyTicketsMessage = buyTicketsMessageService.findBuyTicketsMessageById(id);
        PlaneMessage planeMessage = planeMessageService.findByPlaneId(buyTicketsMessage.getPlaneId());
        LocalDateTime endTime = planeMessage.getStartTime();
        if (endTime.isBefore(LocalDateTime.now())){
            return Result.fail("飞机已起飞，无法换票");
        }
        if (buyTicketsMessage.getTicketState().equals("换购")){
            return Result.fail("已换购的票无法再进行换购");
        }
        session.setAttribute("CHANGE_TICKETS",buyTicketsMessage);
        return Result.ok();
    }
    //获取session中的用户信息进行查询，查找用户的购票信息并展示
    @PostMapping("/userMessage/buyTickets")
    public Result userTicketsMessage(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        UserMessage userMessage = (UserMessage) session.getAttribute("USER_MESSAGE");

        if (userMessage==null){
            return Result.fail("请登录后查看");
        }
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("username",userMessage.getUsername());
        List<BuyTicketsMessage> userTicketsMessages = buyTicketsMessageService.getUserBuyTicketsMessages(queryMap);
        return Result.ok(userTicketsMessages);
    }

    @GetMapping("/delByUsername/{username}")
    public Result delUserMessageByUsername(@PathVariable String username){
        boolean message = userMessageService.delUserMessageByUsername(username);
        if (message){
            return Result.ok("删除成功");
        }else {
            return Result.fail("找不到所要删除的用户名");
        }
    }

    @ResponseBody
    @GetMapping("/userMessages")
    public Result userMessages(@RequestParam(value = "username",required = false) String username,
                               @RequestParam(value = "phone",required = false) String phone){
//        HttpSession session = request.getSession(true);
//        Admin admin = (Admin) session.getAttribute("ADMIN_MESSAGE");
//        System.out.println(admin);
//        if (admin == null){return Result.fail("未登录，无法查看用户数据");}
        Map<String, Object> queryMap = new HashMap<>();

        queryMap.put("username",username);
        queryMap.put("phone",phone);

        List<UserMessage> userMessageList = userMessageService.findAllUserMessage(queryMap);

        return Result.ok(userMessageList);
    }

    @ResponseBody
    @GetMapping("/editUserMessage")
    public Result editUserMessage(@RequestParam(value = "username") String username,
                                  @RequestParam(value = "password") String password,
                                  @RequestParam(value = "balance") Float balance,
                                  @RequestParam(value = "phone") String phone,
                                  @RequestParam(value = "permissions") String permissions){
        if (message == null){return Result.fail("请选择一条数据后进行编辑");}
        UserMessage userMessage = new UserMessage();
        userMessage.setUsername(username);
        userMessage.setPassword(password);
        userMessage.setBalance(balance);
        userMessage.setPhone(phone);
        userMessage.setPermissions(permissions);
        if (!message.getUsername().equals(username)){
            if (userMessageService.getUserMessageByUsername(username)!=null){
                return Result.fail("该用户名存在，修改失败");
            }
            userMessageService.delUserMessageByUsername(message.getUsername());
        }

        userMessageService.saveUserMessage(userMessage);
        message = null;
        return Result.ok();
    }

    @PostMapping("/saveEditUserMessage/{username}")
    public Result saveEditUserMessage(@PathVariable String username){
        UserMessage userMessage = userMessageService.getUserMessageByUsername(username);
        message = userMessage;
        return Result.ok();
    }

    @GetMapping("/plane/planeFind")
    public Result userMessageFindPlane(@RequestParam(value = "planeId") String planeId){
        PlaneMessage planeMessage = planeMessageService.findByPlaneId(planeId);
        List<PlaneMessage> planeMessageList = new ArrayList<>();
        planeMessageList.add(planeMessage);
        return Result.ok(planeMessageList);
    }
}
